#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
从 dictionary.ts 提取词典的 tags 信息并更新到数据库
"""

import json
import re
import pymysql

DB_CONFIG = {
    'host': '127.0.0.1',
    'port': 3306,
    'user': 'root',
    'password': '123',
    'database': 'ry-vue',
    'charset': 'utf8mb4'
}

def parse_dictionary_ts(file_path):
    """解析 dictionary.ts 文件提取词典信息"""
    with open(file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 存储词典信息
    dictionaries = []
    
    # 匹配词典对象的正则表达式
    # 匹配 { id: 'xxx', name: 'xxx', tags: ['tag1', 'tag2'], ... }
    dict_pattern = r'\{\s*id:\s*[\'"]([^\'"]+)[\'"].*?tags:\s*\[([^\]]*)\]'
    
    for match in re.finditer(dict_pattern, content, re.DOTALL):
        dict_id = match.group(1)
        tags_str = match.group(2)
        
        # 解析tags数组
        tags = []
        if tags_str:
            # 提取所有引号中的内容
            tag_matches = re.findall(r'[\'"]([^\'"]+)[\'"]', tags_str)
            tags = tag_matches
        
        dictionaries.append({
            'id': dict_id,
            'tags': tags
        })
    
    return dictionaries

def update_dict_tags():
    """更新数据库中的词典tags"""
    # 解析 dictionary.ts
    ts_file = '/root/workspace/3.1.0-dev/work/aiword/src/resources/dictionary.ts'
    print(f"解析文件: {ts_file}")
    
    dictionaries = parse_dictionary_ts(ts_file)
    print(f"找到 {len(dictionaries)} 个词典定义")
    
    # 连接数据库
    conn = pymysql.connect(**DB_CONFIG)
    try:
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # 获取数据库中的所有词典
            cursor.execute("SELECT id, name FROM dict_book")
            db_books = {row['id']: row['name'] for row in cursor.fetchall()}
            
            updated = 0
            not_found = 0
            
            for dict_info in dictionaries:
                dict_id = dict_info['id']
                tags = dict_info['tags']
                
                if dict_id in db_books:
                    # tags数组转JSON字符串存储
                    tags_json = json.dumps(tags, ensure_ascii=False)
                    
                    # 更新tags（通过dict_book_tag表）
                    # 先删除旧的标签关联
                    cursor.execute("DELETE FROM dict_book_tag WHERE book_id = %s", (dict_id,))
                    
                    # 为每个tag创建或获取tag_id
                    for tag in tags:
                        # 检查标签是否存在
                        cursor.execute("SELECT id FROM dict_tag WHERE name = %s", (tag,))
                        tag_row = cursor.fetchone()
                        
                        if tag_row:
                            tag_id = tag_row['id']
                        else:
                            # 创建新标签
                            cursor.execute(
                                "INSERT INTO dict_tag (name, create_by, create_time) VALUES (%s, 'system', NOW())",
                                (tag,)
                            )
                            tag_id = cursor.lastrowid
                        
                        # 创建词典-标签关联
                        cursor.execute(
                            "INSERT IGNORE INTO dict_book_tag (book_id, tag_id) VALUES (%s, %s)",
                            (dict_id, tag_id)
                        )
                    
                    updated += 1
                    print(f"✓ 更新: {dict_id} ({db_books[dict_id]}) - tags: {tags}")
                else:
                    not_found += 1
                    if dict_id.startswith(('primary', 'junior', 'senior')):  # 小学、初中、高中词典可能没导入
                        continue
                    print(f"⚠ 未找到: {dict_id}")
            
            conn.commit()
            
            print()
            print("=" * 80)
            print(f"更新完成！")
            print(f"  更新: {updated} 个")
            print(f"  未找到: {not_found} 个")
            print("=" * 80)
            
    finally:
        conn.close()

if __name__ == '__main__':
    update_dict_tags()

